package br.com.ordersys.web.client.modules.main;

import java.util.Date;

import br.com.ordersys.web.client.modules.broker.CallBack;
import br.com.ordersys.web.client.modules.broker.ServiceBroker;
import br.com.ordersys.web.client.modules.broker.ServiceCall;
import br.com.ordersys.web.client.modules.broker.ServiceResponse;
import br.com.ordersys.web.client.modules.events.BroadcastDispatcher;
import br.com.ordersys.web.client.modules.events.BroadcastEvent;
import br.com.ordersys.web.client.modules.events.BroadcastMessage;
import br.com.ordersys.web.client.modules.uicomp.BasicPopup;
import br.com.ordersys.web.client.modules.uicomp.BasicResources;
import br.com.ordersys.web.client.modules.uicomp.FallbackImage;
import br.com.ordersys.web.client.modules.utils.I18nBundle;
import br.com.ordersys.web.client.modules.utils.UIUtils;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.VerticalPanel;

public class PictureUploadForm {
	private BasicPopup popup;
	private FormPanel form;
	private FallbackImage img;
	private Button btnConfirm;
	private boolean imageWasRemoved;
	private I18nBundle i18n = new I18nBundle("mainWindow");

	static{
		BasicResources.INSTANCE.basicStyle().ensureInjected();
	}
	
	public void show() {
		popup = new BasicPopup(i18n.get("title_user_pict_change"), false, true);

		popup.setBodyPanel(buildUI(popup));
		popup.setSize("300px", "200px");

		popup.center();
	}

	private Panel buildUI(final BasicPopup popup) {
		form = new FormPanel();
		UIUtils.setWidgetStyle(form, "padding: 20px 6px 0; width: 100%; height: 100%");
		form.setAction("uploadUserPicture");
		form.setEncoding(FormPanel.ENCODING_MULTIPART);
		form.setMethod(FormPanel.METHOD_POST);

		form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
			@Override
			public void onSubmitComplete(SubmitCompleteEvent e) {
				// ao finalizar a carga da imagem, devemos mostrar a imagem no painel
				img.setUrl("getTmpPicture?t" + new Date().getTime());
				btnConfirm.setEnabled(true);
			}
		});

		HorizontalPanel hMainPanel = new HorizontalPanel();
		hMainPanel.setSpacing(10);
		UIUtils.setWidgetStyle(hMainPanel, "width: 100%; height: 100%");

		addLeftPanel(hMainPanel);

		addRightPanel(hMainPanel);

		form.setWidget(hMainPanel);

		return form;
	}

	private void addRightPanel(HorizontalPanel hMainPanel) {
		DockPanel dockPanel = new DockPanel();
		dockPanel.setHeight("10em"); //sem essa altura literal o IE não renderiza corretamente.
		dockPanel.setWidth("100%");

		VerticalPanel vpnl = new VerticalPanel();

		vpnl.add(new Label(i18n.get("lbl_select_image_file")));

		FileUpload fu = new FileUpload();
		fu.setName("fileContent");
		fu.getElement().setAttribute("accept", "image/png, image/gif,image/jpeg");

		vpnl.add(fu);

		fu.addChangeHandler(new ChangeHandler() {
			@Override
			public void onChange(ChangeEvent e) {
				// ao selecionar o arquivo o sistema o envia para o servidor
				form.submit();
				imageWasRemoved = false;
			}
		});

		Panel buttonsPanel = buildButtonsPanel();

		dockPanel.add(vpnl, DockPanel.NORTH);
		dockPanel.add(buttonsPanel, DockPanel.SOUTH);
		
		dockPanel.setCellVerticalAlignment(buttonsPanel, dockPanel.ALIGN_BOTTOM);
		dockPanel.setCellHorizontalAlignment(buttonsPanel, dockPanel.ALIGN_CENTER);

		hMainPanel.add(dockPanel);
	}

	private void addLeftPanel(HorizontalPanel hMainPanel) {
		img = new FallbackImage("img/user/" + UIUtils.getEnvironment("userId") + "?t=" + new Date().getTime());
		img.setFallbackURL("images/silueta-homen-azul.png");
		img.setSize("10em", "10em");

		VerticalPanel vpnl = new VerticalPanel();
		UIUtils.setWidgetStyle(vpnl, "position: relative; width: 10em; height: 10em"); // precisamos disso para colocar o botão de remover por sobre a foto

		vpnl.add(img);

		FocusPanel trashPnl = new FocusPanel();
		trashPnl.setTitle(i18n.get("lbl_remove_user_pict"));
		trashPnl.addStyleName(BasicResources.INSTANCE.basicStyle().halfTransparentPanel());
		UIUtils.setWidgetStyle(trashPnl, "border: 0px; backgroundColor: #0072C6; height: 2em; width: 100%; position: absolute; bottom: 0px; zIndex: 1; cursor:pointer");

		HTML btnTrash = new HTML();
		btnTrash.setStyleName("");

		UIUtils.setWidgetStyle(btnTrash, "border: 0px; backgroundColor: transparent; backgroundImage: url('images/trash-can.png'); backgroundSize: 100% 100% ;width: 2em; height: 2em");
		trashPnl.setWidget(btnTrash);

		vpnl.add(trashPnl);
		vpnl.setCellHorizontalAlignment(trashPnl, VerticalPanel.ALIGN_CENTER);

		trashPnl.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent e) {
				imageWasRemoved = true;
				img.setUrl("images/silueta-homen-azul.png");
				btnConfirm.setEnabled(true);
			}
		});

		hMainPanel.add(vpnl);
	}

	protected void removePicture() {
		ServiceCall sc = new ServiceCall("user", "removePicture");

		sc.setHandleErrors(true);

		sc.setResponseCallBack(new CallBack() {
			@Override
			public void onResponse(ServiceResponse response) {
				if (response.getStatus() == 0) {
					notifyUserPictureChanged();
					imageWasRemoved = false;
					popup.hide();
				} else {
					Window.alert(response.getMessage());
				}
			}
		});

		ServiceBroker sb = new ServiceBroker();

		sb.call(sc);
	}

	private void notifyUserPictureChanged() {
		BroadcastDispatcher.send(new BroadcastEvent(BroadcastMessage.USER_PICTURE_CHANGED));
	}

	private Panel buildButtonsPanel() {
		HorizontalPanel hpnl = new HorizontalPanel();

		Button btnCancel = new Button(i18n.get("btn_cancel"), new ClickHandler() {
			@Override
			public void onClick(ClickEvent e) {
				popup.hide();
			}
		});

		btnCancel.setStyleName(BasicResources.INSTANCE.basicStyle().defaultButton());

		hpnl.add(btnCancel);

		btnConfirm = new Button(i18n.get("btn_confirm"), new ClickHandler() {
			@Override
			public void onClick(ClickEvent e) {
				saveImage();
			}
		});

		btnConfirm.setStyleName(BasicResources.INSTANCE.basicStyle().defaultButton());
		btnConfirm.setEnabled(false);

		hpnl.add(btnConfirm);

		UIUtils.setParentStyle(btnConfirm, "paddingLeft: 15px");

		return hpnl;
	}

	protected void saveImage() {
		if (imageWasRemoved) {
			removePicture();
		} else {
			ServiceCall sc = new ServiceCall("user", "savePicture");

			sc.setHandleErrors(true);

			sc.setResponseCallBack(new CallBack() {
				@Override
				public void onResponse(ServiceResponse response) {
					if (response.getStatus() == 0) {
						notifyUserPictureChanged();
						popup.hide();
					} else {
						Window.alert(response.getMessage());
					}
				}
			});

			ServiceBroker sb = new ServiceBroker();

			sb.call(sc);
		}

	}
}
